package com.example.androidlearning2200;

import android.content.Context;
import android.media.AudioManager;
import android.media.MediaPlayer;
import android.net.Uri;
import android.util.AttributeSet;
import android.view.GestureDetector;
import android.view.LayoutInflater;
import android.view.MotionEvent;
import android.view.View;
import android.widget.FrameLayout;
import android.widget.ImageView;
import android.widget.TextView;
import android.widget.VideoView;

import androidx.annotation.NonNull;
import androidx.annotation.Nullable;

public class CustomVideoView extends FrameLayout {
    private VideoView vv;
    private ImageView ivPlayOrPause, ivSound;
    private TextView tvTimeElapseAndTotal;

    private MediaPlayer mMediaPlayer;

    // 是否静音
    private boolean isMute = false;

    private GestureDetector gestureDetector;

    private final Runnable timeRunnable = new Runnable() {
        @Override
        public void run() {
            // 更新时间，每一秒刷新一次
            updateTime();
            postDelayed(timeRunnable, 1000);
        }
    };

    /**
     * 更新播放时间的方法
     */
    private void updateTime() {
        if (mMediaPlayer != null) {
            // 总时长
            int duration = mMediaPlayer.getDuration();
            // 播放进度
            int position = mMediaPlayer.getCurrentPosition();
            tvTimeElapseAndTotal.setText(String.format("%02d:%02d/%02d:%02d", position / 1000 / 60, position / 1000 % 60, duration / 1000 / 60, duration / 1000 % 60));
        }
    }

    public CustomVideoView(@NonNull Context context) {
        super(context);
        initView(context);
        post(timeRunnable);
    }

    public CustomVideoView(@NonNull Context context, @Nullable AttributeSet attrs) {
        super(context, attrs);
        initView(context);
        post(timeRunnable);
    }

    /**
     * 根据布局文件，初始化自定义控件
     *
     * @param context
     */
    private void initView(@NonNull Context context) {
        LayoutInflater.from(context).inflate(R.layout.layout_custom_video_view, this, true);
        vv = findViewById(R.id.vv);
        ivPlayOrPause = findViewById(R.id.ivPlayOrPause);
        ivSound = findViewById(R.id.ivSound);
        tvTimeElapseAndTotal = findViewById(R.id.tvTimeElapseAndTotal);
        vv.setOnPreparedListener(new MediaPlayer.OnPreparedListener() {
            @Override
            public void onPrepared(MediaPlayer mediaPlayer) {
                // 视频播放之前
                mMediaPlayer = mediaPlayer;
                mMediaPlayer.start();
            }
        });
        vv.setOnCompletionListener(new MediaPlayer.OnCompletionListener() {
            @Override
            public void onCompletion(MediaPlayer mediaPlayer) {
                // 视频播放完成
            }
        });
        ivPlayOrPause.setOnClickListener(new OnClickListener() {
            @Override
            public void onClick(View view) {
                doPlayOrPause();
            }
        });
        ivSound.setOnClickListener(new OnClickListener() {
            @Override
            public void onClick(View view) {
                AudioManager audioManager = (AudioManager) context.getSystemService(Context.AUDIO_SERVICE);
                if (isMute) {
                    // 当前时静音状态
                    audioManager.setStreamMute(AudioManager.STREAM_MUSIC, false);
                    ivSound.setImageResource(R.mipmap.ic_mute);
                    isMute = false;
                } else {
                    // 当前时非静音状态
                    audioManager.setStreamMute(AudioManager.STREAM_MUSIC, true);
                    ivSound.setImageResource(R.mipmap.ic_unmute);
                    isMute = true;
                }
            }
        });
        gestureDetector = new GestureDetector(context, new GestureDetector.SimpleOnGestureListener() {
            @Override
            public void onShowPress(@NonNull MotionEvent e) {
                super.onShowPress(e);
                // 长按,二倍速播放
                setPlaySpeed(mMediaPlayer, 2.0f);
            }

            @Override
            public boolean onDoubleTap(@NonNull MotionEvent e) {
                // 双击
                doPlayOrPause();
                return true;
            }
        });
        vv.setOnTouchListener(new OnTouchListener() {
            @Override
            public boolean onTouch(View view, MotionEvent motionEvent) {
                switch (motionEvent.getAction()) {
                    case MotionEvent.ACTION_UP:
                        // 只有触摸后抬起，就设置为1倍速
                        setPlaySpeed(mMediaPlayer, 1.0f);
                        break;
                }
                gestureDetector.onTouchEvent(motionEvent);
                return true;
            }
        });
    }

    /**
     * 处理暂停与播放
     */
    private void doPlayOrPause() {
        if (mMediaPlayer.isPlaying()) {
            // 正在播放时点击，需要暂停，且图标换成播放图标
            mMediaPlayer.pause();
            ivPlayOrPause.setImageResource(R.mipmap.ic_play_z);
        } else {
            // 暂停状态时点击，需要播放，且图标缓存暂停图标
            mMediaPlayer.start();
            ivPlayOrPause.setImageResource(R.mipmap.ic_pause_z);
        }
    }

    /**
     * 对外暴露设置视频资源的方法
     *
     * @param uri
     */
    public void setVideoUri(Uri uri) {
        vv.setVideoURI(uri);
    }

    /**
     * 销毁更新播放时间的Runnable
     */
    public void destroy() {
        if (mMediaPlayer != null) {
            removeCallbacks(timeRunnable);
        }
    }

    /**
     * 设置播放速度
     *
     * @param mediaPlayer
     * @param speed
     */
    private void setPlaySpeed(MediaPlayer mediaPlayer, float speed) {
        if (mediaPlayer.isPlaying()) {
            mediaPlayer.setPlaybackParams(mediaPlayer.getPlaybackParams().setSpeed(speed));
        } else {
            mediaPlayer.setPlaybackParams(mediaPlayer.getPlaybackParams().setSpeed(speed));
            mediaPlayer.pause();
        }
    }

}
